package com.tinusgraglin.enclusiv

import android.app.Application
import android.content.Context
import coil.ImageLoader
import coil.disk.DiskCache
import coil.memory.MemoryCache
import com.tinusgraglin.enclusiv.datalayer.*
import com.tinusgraglin.enclusiv.datalayer.datasources.ArticleRemoteSource
import com.tinusgraglin.enclusiv.datalayer.datasources.PicsRemoteSource
import com.tinusgraglin.enclusiv.datalayer.datasources.UserDataStatsRemoteSource
import com.tinusgraglin.enclusiv.datalayer.datasources.UserRegistrationRemoteSource
import com.tinusgraglin.enclusiv.datalayer.repos.ArticleRepo
import com.tinusgraglin.enclusiv.datalayer.repos.GlobalPrefDataRepo
import com.tinusgraglin.enclusiv.datalayer.repos.UserRepo
import okhttp3.HttpUrl.Companion.toHttpUrl

class EnclusivApp : Application() {
    companion object {
        lateinit var appContext: Context
            private set
        lateinit var globalRemoteSourceCommunication: RemoteSourceCommunication
            private set
        lateinit var globalCoilImageLoader: ImageLoader
            private set
    }

    override fun onCreate() {
        super.onCreate()
        appContext = applicationContext
        globalRemoteSourceCommunication = RemoteSourceCommunication(getString(R.string.main_server_url).toHttpUrl())

        globalCoilImageLoader = ImageLoader(appContext).newBuilder().apply {
            okHttpClient(globalRemoteSourceCommunication.client)
            crossfade(true)
            memoryCache {
                MemoryCache.Builder(appContext)
                    .maxSizePercent(0.25)
                    .build()
                }
            diskCache {
                DiskCache.Builder()
                    .directory(appContext.cacheDir.resolve("image_cache"))
                    .maxSizePercent(0.02)
                    .build()
                }
        }.build()

        GlobalPrefDataRepo.initialize(applicationContext)

        UserRepo.initialize(
            UserRegistrationRemoteSource(globalRemoteSourceCommunication),
            UserDataStatsRemoteSource(globalRemoteSourceCommunication)
        )
        ArticleRepo.initialize(
            ArticleRemoteSource(globalRemoteSourceCommunication),
            PicsRemoteSource(globalRemoteSourceCommunication)
        )
    }
}